import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import { login, logout, getInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(Cookies.get('token') || '')
  const userInfo = ref({})
  const roles = ref([])
  const permissions = ref([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasRole = computed(() => (role) => roles.value.includes(role))
  const hasPermission = computed(() => (permission) => permissions.value.includes(permission))

  // 登录
  const loginAction = async (loginForm) => {
    try {
      const { token: userToken } = await login(loginForm)
      token.value = userToken
      Cookies.set('token', userToken, { expires: 7 })
      return userToken
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息
  const getInfoAction = async () => {
    try {
      const data = await getInfo()
      userInfo.value = data.user
      roles.value = data.roles || []
      permissions.value = data.permissions || []
      return data
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      resetUserInfo()
    }
  }

  // 重置用户信息
  const resetUserInfo = () => {
    token.value = ''
    userInfo.value = {}
    roles.value = []
    permissions.value = []
    Cookies.remove('token')
  }

  // 设置token
  const setToken = (userToken) => {
    token.value = userToken
    Cookies.set('token', userToken, { expires: 7 })
  }

  return {
    // 状态
    token,
    userInfo,
    roles,
    permissions,
    
    // 计算属性
    isLoggedIn,
    hasRole,
    hasPermission,
    
    // 方法
    loginAction,
    getInfoAction,
    logoutAction,
    resetUserInfo,
    setToken
  }
})
